<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
 *The data diff
 * @param date   $startdate
 * @param date   $enddate
 * @return string
 */


 function uuid($prefix = ""){    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str,0,8) . '-';
    $uuid .= substr($str,8,4) . '-';
    $uuid .= substr($str,12,4) . '-';
    $uuid .= substr($str,16,4) . '-';
    $uuid .= substr($str,20,12);
    return $prefix . $uuid;
}
 function uuorder($prefix = ""){
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
	return $prefix . $orderSn;
 }

  function get_date_diff($start,$end){
	   	$startdate=strtotime($start);
	   	$enddate=strtotime($end);
	   	if($startdate >= $enddate) {
	   		$days = round(($enddate-$startdate)/3600/24);
	   	}else{
	   		$days = 0;
	   	}
	   	return $days;
   }

 function generate_random_string($length = 10) {

		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {

			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}

	/**
	 *The data
	 * @param   null
	 * @return string 日期路径
	 */

   function getDatePath() {

		$date=getdate();
		$month=$date["mon"];
		if ($month <10) {
			$month="0".$date["mon"];
		}

		$day = $date["mday"];
		if($day <10) {

			$day="0".$date["mday"];
		}

		$path=$date["year"].$month.$day;
		  return $path ;
  }


	/**
	 *The data package according to their relationship
	 * @param array   $tree include key id,parent_id
	 * @param integer|null   $rootId
	 * @return array
	 */

    function arr2tree($tree, $rootId = 0) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['parent_id'] == $rootId) {
                foreach($tree as $subleaf) {
                    if($subleaf['parent_id'] == $leaf['id']) {
                        $leaf['menus'] = arr2tree($tree, $leaf['id']);
                        break;
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }

    function get_all_department($tree, $rootId = 0) {
        $return = array();
        foreach($tree as $leaf) {
            if($leaf['parent_id'] == $rootId) {
                foreach($tree as $subleaf) {
                    if($subleaf['parent_id'] == $leaf['id']) {
                        $return =array_merge($return,get_all_department($tree, $leaf['id']));
                        break;
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }

    /**
     *
     * @param array   $tree include key id,parent_id
     * @param integer|null   $rootId
     * @return json
     */
    function arr_tree($tree, $rootId = "0") {
    	$return = array();
    	foreach($tree as $leaf) {
    		if($leaf['id'] !== "" && $leaf['parent_id'] === $rootId) {
    			foreach($tree as $subleaf) {
    				if($subleaf['id'] !== "" && $subleaf['parent_id'] === $leaf['id']) {
    					$leaf['children'] = arr_tree($tree, $leaf['id']);
    					break;
    				}else{
    					unset($leaf['parent_id']);

    				}
    			}
    			$return[] = $leaf;

    		}
    	}
    	return $return;
    }


    function arrtree($tree, $rootId = 0) {
    	$return = array();
    	foreach($tree as $leaf) {
    		if($leaf['parent_id'] == $rootId) {
    			foreach($tree as $subleaf) {
    				if($subleaf['parent_id'] == $leaf['id']) {

    					$leaf['children'] = arr_tree($tree, $leaf['id']);

    					break;
    				}else{
    					unset($leaf['parent_id']);

    				}
    			}

    			$return[] = $leaf;

    		}
    	}
    	return $return;
    }



    // The data show once again using HTML
    function tree2html($tree) {
        echo '<ul>';
        foreach($tree as $leaf) {
            if($leaf['level'] ==3){
        	   echo '<li class="group_auth">' .'<input type="checkbox" name="check_set" value="'.$leaf['id'].'"  />'.$leaf['name']."&nbsp;&nbsp;&nbsp;&nbsp;";
            }else{
            	echo '<li >' .'<input type="checkbox" name="check_set" value="'.$leaf['id'].'"  />'.$leaf['name'];
            }
            if(! empty($leaf['menus'])) tree2html($leaf['menus']);
            echo '</li>';
        }
        echo '</ul><br>';
    }



    function arr_sort($arr,$parent_id = 0,$lev=1) {
        static $list = array();
        static $num = 0;
        foreach($arr as $v) {
            echo ++$num . '<br />';
            if($v['parent_id'] == $parent_id) {
                $num = 0;
                $v['lev'] = $lev;
                $list[] = $v;
                catsort($arr,$v['id'],$lev+1);
            }
        }
        return $list;
    }

    //打印格式化数组
    function p($res){
        echo "<pre>";
        if(is_array($res)){
        	print_r($res);
        }else{
        	echo "<font size='300px'>".$res."</font>";
        }
        die;
    }


    //打印格式化数组
    function s($res){
        echo "<pre>";
         if(is_array($res)){
        	print_r($res);
        }else{
        	echo "<font size='300px'>".$res."</font>";
        }
    }

    /*
     * 发送短信
     * @param $telephone 电话
     * @param $content_type 消息的种类
     * @param $replace_content 具体内容,替换配置文件的{content}
     * */
    function send_msg($telephone,$content_type,$replace_content=''){
        $ci=&get_instance();
        $sms_config=get_my_config('myconfig/site_config','send_msg');
        $url=$sms_config['url'];
        $username=$sms_config['username'];
        $password=$sms_config['password'];
        $content=$sms_config[$content_type];
        $params['userName']=$username;
        $params['password']=$password;
        $params['telphone']=$telephone;
        $params['content']=str_replace('{content}',$replace_content,$content);
        $params['content']=iconv('utf-8','gb2312',$params['content']);
        $res=curl_http_request($url,$params,'post');
        //处理发送短信以后的返回结果
        if(strpos($res,'success')!==FALSE){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    //生成6位随机数
    function rands(){
        return rand(100000,999999);
    }


    /*
     * curl提交请求
     * @param url地址 $url
     * @param array $params
     * @param type get/post
     * */
    function curl_http_request($url,$params,$type){
        if(is_array($params) && !empty($params)){
            $params=http_build_query ( $params, '&' );
        }else{
            $params = "";
        }

        if("GET" == strtoupper($type)){
            $url .= "?".$params;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            $return = curl_exec($ch);
            curl_close($ch);
        }else{
            $ch = curl_init ();
            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt ( $ch, CURLOPT_URL, $url );
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
            $return = curl_exec ( $ch );
            curl_close ( $ch );
        }
        return $return;
    }

     function get_childrens($data){

        $childrens=  sonCategoryIds($data);
        return $childrens;
    }
     function sonCategoryIds($categoryID)
    {
        $ci=&get_instance();
        $array[] = '';

        $ids = '';
        // $temp = $this->mysql->select('SELECT `id` FROM `pcb_article_category` WHERE `parentID` IN (' . $categoryID . ')');
        //  $temp=$this->table_model->get_array_where_in('department','pid',$categoryID);
        $ci->db->select('id');
        $ci->db->from('department');
        $ci->db->where(array('company_id'=> $ci->company_id));
        $ci->db->like('path', ','.$categoryID.',', 'both');
        $temp= $ci->db->get()->result_array();
        foreach ($temp as $v)
        {
            $array[] = $v['id'];
            $ids .= ',' . $v['id'];
        }
        $ids = substr($ids, 1, strlen($ids));
        $categoryID = $ids;


        $ids = implode(',', $array);

        return $ids;
    }

    /*
     * 获取客户端参数的方法
     * */
    function get_param($key){
        $ci =& get_instance();
        $param=trim($ci->input->get($key));
        return $param;
    }

    /*
     * json返回
     * */
    function json_return($status,$msg,$rows=''){
        if($rows==''){
            echo json_encode(array('status'=>$status,'msg'=>$msg));
            die;
        }else{
            echo json_encode(array('status'=>$status,'msg'=>$msg,'rows'=>$rows));
            die;
        }
    }
    /*
	 * 获取2个经纬度之间的距离
	 * */
    function getDistance($lat1, $lng1, $lat2, $lng2){
            $earthRadius = 6371000; //approximate radius of earth in meters
            $lat1 = ($lat1 * pi() ) / 180;
            $lng1 = ($lng1 * pi() ) / 180;

            $lat2 = ($lat2 * pi() ) / 180;
            $lng2 = ($lng2 * pi() ) / 180;

            $calcLongitude = $lng2 - $lng1;
            $calcLatitude = $lat2 - $lat1;
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
            $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
            $calculatedDistance = $earthRadius * $stepTwo;
            return round($calculatedDistance);
}
    /*
     * 获取定义的config参数
     * */
    function get_my_config($path,$arr_name){
        $ci = & get_instance();
        $ci->load->config($path,true);
        return $ci->config->item($arr_name,$path);
    }

    /*
     * 极光提送
     * @$id_array 用户id
     * @title 标题
     * @content 内容
     * @extras array('type'=>'推送的类型','关键字'=>'值')
     * */
    function jpush($id_array,$title,$content,$extras=array()){
        $type=$extras['type'];
        if(strpos($type,'leave')!==false){
            $id_array=see_jpush($id_array,'is_leave');
        }elseif(strpos($type,'trip')!==false){
            $id_array=see_jpush($id_array,'is_trip');
        }elseif(strpos($type,'overtime')!==false){
            $id_array=see_jpush($id_array,'is_overtime');
        }elseif(strpos($type,'meeting')!==false){
            $id_array=see_jpush($id_array,'is_meeting');
        }elseif(strpos($type,'place')!==false){
            $id_array=see_jpush($id_array,'is_record');
        }
        $params='platform=all';
        //发送的设备id
        $to['alias']=$id_array;
//        $to['alias']=array(495,492);
        $params.='&audience='.json_encode($to);
//        $params.='&audience=all';
        $notice['android']=array(
            "alert" => $content,
             "title"  => $title,
             "builder_id"  => 1,
             "extras"  => $extras
        );
        $notice['ios']=array(
            "alert" => $content,
            "sound"=>"default",
//            "badge"=>"+1",
            "extras" => $extras
        );
        $options=array(
            "apns_production"=>true
        );
        $params.='&notification='.json_encode($notice);
        $params.='&options='.json_encode($options);
        jpush_post($params);
    }

   /*
     * jpush post 方法
     * */
    function jpush_post($params){
        $jpush_config=get_my_config('myconfig/site_config','jpush_config');
        $base64_auth_string=base64_encode($jpush_config['appkeys'].':'.$jpush_config['mastersecret']);//正式服的推送代码
//        $base64_auth_string=base64_encode('d7c572c08ce40df773399200:334340928c5ae6a1e03c1de0');//ios测试推送代码
        $header=array("Authorization:Basic $base64_auth_string");
        $postUrl = $jpush_config['jpush_url'];
        $curlPost = $params;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);

        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);//传递头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    /*
     * 获取用户设备类型的数组
     * $ids=1,2,3
     * */
    function get_device_type($id_array){
        $ci=&get_instance();
        $query=$ci->db->from('employee')->select('user_id,device_type')->where_in('user_id',$id_array)->get();
        if($query->num_rows()==0){
            return array();
        }else{
            $arr=$query->result();
            for($i=0;$i<count($arr);$i++){
                $return_arr[]=array('user_id'=>$arr[$i]->user_id,'device_type'=>$arr[$i]->device_type);
            }
            return $return_arr;
        }
    }
/*
 * 查看激光推送是否发送
 * $arruser user数组
 * $condition 是例如is_overtime
 * return 一维user数组
 * */
function see_jpush($arruser,$condition){
    $ci=&get_instance();
    $arr=array();
    $new_arr=array();
    foreach($arruser as $k=>$v) {

        $ci->db->select('*');
        $ci->db->from('user_push');
        $ci->db->where(array('user_id' =>$v));
        $query = $ci->db->get();
        $res = $query->result_array();
       /* echo "<pre>";
        print_r($res);
        echo $condition;*/
        if(!$res){
            continue;
        }
        $times = date('H:m', time());
        if ($res[0]['is_push'] == 1) {
            if ($res[0]['is_disturb'] == 1 && $times > $res[0]['start'] && $times < $res[0]['end']) {

            }else {
                 if($res[0][$condition]==1){
                     $new_arr[]=$v;
                 }
            }
        }
    }
    return $new_arr;

}


/*
 * 把激光推送设置保存到数据库
 * */

    function set_jpush($user_id,$is_push="",$is_leave="",$is_overtime="",$is_trip="",$is_record="",$is_meeting="",$is_disturb="",$start="",$end=""){
        $ci=&get_instance();
        $ci->db->select('*');
        $ci->db->from('user_push');
        $ci->db->where(array('user_id'=>$user_id));
        $query=$ci->db->get();
        $res=$query->result_array();
        if(!$res){//新用户增加
            $ci->db->insert('user_push',array('user_id'=>$user_id));

           return TRUE;
        }else{//原用户修改
            $data=array();
            if($is_push!=""){
                $data['is_push']=$is_push;
            }
            if($is_leave!=""){
                $data['is_leave']=$is_leave;
            }
            if($is_overtime!=""){
                $data['is_overtime']=$is_overtime;
            }
            if($is_trip!=""){
                $data['is_trip']=$is_trip;
            }
            if($is_record!=""){
                $data['is_record']=$is_record;
            }
            if($is_meeting!=""){
                $data['is_meeting']=$is_meeting;
            }
            if($is_disturb!=""){
                $data['is_disturb']=$is_disturb;
            }
            if($start!=""){
                $data['start']=$start;
            }
            if($end!=""){
                $data['end']=$end;
            }
            //print_r($data);
            if($data==NULL){
                return FALSE;

            }
            $ci->db->where(array('user_id'=>$user_id));
            $ci->db->update('user_push',$data);

             return TRUE;
        }


    }



/*
 * 每个月多少天
 * @return string
 * */
function getMonthLastDay($month, $year) {
    switch ($month) {
        case 4 :
        case 6 :
        case 9 :
        case 11 :
            $days = 30;
            break;
        case 2 :
            if ($year % 4 == 0) {
                if ($year % 100 == 0) {
                    $days = $year % 400 == 0 ? 29 : 28;
                } else {
                    $days = 29;
                }
            } else {
                $days = 28;
            }
            break;

        default :
            $days = 31;
            break;
    }
    return $days;
}


/*
 * 每个月周末的总天数
 * @return string
 * */
function get_weekend_days($start_date,$end_date,$is_workday = false){

    if (strtotime($start_date) > strtotime($end_date)) list($start_date, $end_date) = array($end_date, $start_date);
    $start_reduce = $end_add = 0;
    $start_N = date('N',strtotime($start_date));
    $start_reduce = ($start_N == 7) ? 1 : 0;
    $end_N = date('N',strtotime($end_date));
    in_array($end_N,array(6,7)) && $end_add = ($end_N == 7) ? 2 : 1;
    $alldays = abs(strtotime($end_date) - strtotime($start_date))/86400 + 1;
    $weekend_days = floor(($alldays + $start_N - 1 - $end_N) / 7) * 2 - $start_reduce + $end_add;
    if ($is_workday){
        $workday_days = $alldays - $weekend_days;
        return $workday_days;
    }
    return $weekend_days;
}
//把汉字转化成拼音 第二个参数任意为UTF8 不传为gb2312
function pinyin($_String, $_Code='gb2312')
{
    $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".
        "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".
        "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".
        "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".
        "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".
        "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".
        "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".
        "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".
        "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".
        "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".
        "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".
        "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".
        "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".
        "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".
        "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".
        "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
    $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".
        "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".
        "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".
        "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".
        "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".
        "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".
        "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".
        "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".
        "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".
        "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".
        "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".
        "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".
        "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".
        "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".
        "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".
        "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".
        "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".
        "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".
        "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".
        "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".
        "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".
        "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".
        "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".
        "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".
        "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".
        "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".
        "|-10270|-10262|-10260|-10256|-10254";
    $_TDataKey = explode('|', $_DataKey);
    $_TDataValue = explode('|', $_DataValue);
    $_Data = (PHP_VERSION>='5.0') ? array_combine($_TDataKey, $_TDataValue) : _Array_Combine($_TDataKey, $_TDataValue);
    arsort($_Data);
    reset($_Data);
    if($_Code != 'gb2312') $_String = _U2_Utf8_Gb($_String);
    $_Res = '';
    for($i=0; $i<strlen($_String); $i++)
    {
        $_P = ord(substr($_String, $i, 1));
        if($_P>160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; }
        $_Res .= _Pinyin($_P, $_Data);
    }
    return preg_replace("/[^a-z0-9]*/", '', $_Res);
}//拼音
function _Pinyin($_Num, $_Data)
{
    if ($_Num>0 && $_Num<160 ) return chr($_Num);
    elseif($_Num<-20319 || $_Num>-10247) return '';
    else {
        foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
        return $k;
    }
}//拼音
function _U2_Utf8_Gb($_C)
{
    $_String = '';
    if($_C < 0x80) $_String .= $_C;
    elseif($_C < 0x800)
    {
        $_String .= chr(0xC0 | $_C>>6);
        $_String .= chr(0x80 | $_C & 0x3F);
    }elseif($_C < 0x10000){
        $_String .= chr(0xE0 | $_C>>12);
        $_String .= chr(0x80 | $_C>>6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
    } elseif($_C < 0x200000) {
        $_String .= chr(0xF0 | $_C>>18);
        $_String .= chr(0x80 | $_C>>12 & 0x3F);
        $_String .= chr(0x80 | $_C>>6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
    }
    return iconv('UTF-8', 'GB2312', $_String);
}//拼音
function _Array_Combine($_Arr1, $_Arr2)
{
    for($i=0; $i<count($_Arr1); $i++) $_Res[$_Arr1[$i]] = $_Arr2[$i];
    return $_Res;
}


/*
 * 递归获取id列表,在标注里面获取地点
 * */
function get_id_list(){}

/*
 * 判断是否是微信浏览器
 *
 * */
function check_user_agent(){
    if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')===FALSE){
//        $weObj = new Wechat(get_my_config('myconfig/site_config','wx'));
//        $res=$weObj->getOauthRedirect(site_url('/wx/wx_login/test'));
//        header('Location: '.$res);
//        die;
        wx_url();
    }
}

/*
 * 非微信浏览器,或者openid不存在,或者换取的code不存在进入的url
 * */
function wx_url($controller_path='wx/wx_login/index',$status='',$scope='snsapi_base'){
    $weObj = new Wechat(get_my_config('myconfig/site_config','wx'));
    $res=$weObj->getOauthRedirect(site_url($controller_path),$status,$scope);
    header('Location: '.$res);
    die;
}

/*
 * 清空数组中的为空的元素
 * */
function array_del_null($arr){
    $return_arr=array();
    for($i=0;$i<count($arr);$i++){
        if($arr[$i]==''||$arr[$i]==NULL||$arr[$i]==0){
            continue;
        }else{
            $return_arr[]=$arr[$i];
        }
    }
    return $return_arr;
}

/*
 * post获取参数
 * */
function post($str){
    $ci=&get_instance();
    return $ci->input->post($str);
}

/*
 * get获取参数
 * */
function get($str){
    $ci=&get_instance();
    return $ci->input->get($str);
}


/*
 * 验证手机
 * @params $telephone 手机号码
 * */
function check_telephone($telephone){
    $array=array('telephone'=>$telephone);
    $ci=& get_instance();
    $ci->form_validation->set_data($array);
    $ci->form_validation->set_rules('telephone','手机','trim|required|regex_match[/^1[34578]{1}[0-9]{9}$/]');
    if($ci->form_validation->run()===FALSE){
        json_return('error','手机号码格式错误');
    }
}

/*
 * 判断非空
 * @params $type 手机号码
 * */
function check_null($str,$field_name){
    $array=array('str'=>$str);
    $ci=& get_instance();
    $ci->form_validation->set_data($array);
    $ci->form_validation->set_rules('str','','trim|required');
    if($ci->form_validation->run()===FALSE){
        json_return('error',$field_name.'不能为空');
    }
}

/*
 * 最小长度
 * */
function check_min_length($str,$field_name,$minlength){
    $array=array('str'=>$str);
    $ci=& get_instance();
    $ci->form_validation->set_data($array);
    $ci->form_validation->set_rules('str','','trim|required|min_length['.intval($minlength).']');
    if($ci->form_validation->run()===FALSE){
        json_return('error',$field_name.'长度不能少于'.$minlength);
    }
}

/*
 * 数字判断
 * */
function check_number($str){
    $array=array('str'=>$str);
    $ci=& get_instance();
    $ci->form_validation->set_data($array);
    $ci->form_validation->set_rules('str','','trim|required|regex_match[/^\d+$/]');
    if($ci->form_validation->run()===FALSE){
        json_return('error','非数字');
    }
}

/*
 * 错误页面
 * */
function error($str,$type=0){
    echo $str;
    die;
}


/*
 * 提交方式 post/get
 * */
function method(){
    return 'post';
}


/**
* 缩略图主函数
* @param string $src 图片路径
* @param int $w 缩略图宽�?
* @param int $h 缩略图高�?
* @return mixed 返回缩略图路�?
* **/
function resize($src,$savepath,$w,$h="")
{
    $temp=pathinfo($src);
    $name=$temp["basename"];//文件�?
    $dir=$temp["dirname"];//文件所在的文件�?
    $extension=$temp["extension"];//文件扩展�?
    //$savepath="{$dir}/{$name}";//缩略图保存路�?新的文件名为*.thumb.jpg

    //获取图片的基本信�?
    $info=getImageInfo($src);
    $width=$info[0];//获取图片宽度
    $height=$info[1];//获取图片高度
    $per1=round($width/$height,2);//计算原图长宽�?
    //$per2=round($w/$h,2);//计算缩略图长宽比
	$per2 = $per1;
    /*
    //计算缩放比例
    if($per1>$per2||$per1==$per2)
    {
        //原图长宽比大于或者等于缩略图长宽比，则按照宽度优�?
        $per=$w/$width;
    }
    if($per1<$per2)
    {
        //原图长宽比小于缩略图长宽比，则按照高度优�?
        $per=$h/$height;
    }
    */
    //$temp_w=intval($width*$per);//计算原图缩放后的宽度
    //$temp_h=intval($height*$per);//计算原图缩放后的高度
    $temp_w=intval($w);//计算原图缩放后的宽度
    $temp_h=intval($height*$w/$width);//计算原图缩放后的高度
    $temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布
    $im=create($src);
    imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);
    if($per1>$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return addBg($savepath,$w,$h,"w");
        //宽度优先，在缩放之后高度不足的情况下补上背景
    }
    if($per1==$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return $savepath;
        //等比缩放
    }
    if($per1<$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return addBg($savepath,$w,$h,"h");
        //高度优先，在缩放之后宽度不足的情况下补上背景
    }
}
/**
* 添加背景
* @param string $src 图片路径
* @param int $w 背景图像宽度
* @param int $h 背景图像高度
* @param String $first 决定图像最终位置的，w 宽度优先 h 高度优先 wh:等比
* @return 返回加上背景的图�?
* **/
function addBg($src,$w,$h,$fisrt="w")
{
    $bg=imagecreatetruecolor($w,$h);
    $white = imagecolorallocate($bg,255,255,255);
    imagefill($bg,0,0,$white);//填充背景

    //获取目标图片信息
    $info=getImageInfo($src);
    $width=$info[0];//目标图片宽度
    $height=$info[1];//目标图片高度
    $img=create($src);
    if($fisrt=="wh")
    {
        //等比缩放
        return $src;
    }
    else
    {
        if($fisrt=="w")
        {
            $x=0;
            $y=($h-$height)/2;//垂直居中
        }
        if($fisrt=="h")
        {
            $x=($w-$width)/2;//水平居中
            $y=0;
        }
        imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
        imagejpeg($bg,$src,100);
        imagedestroy($bg);
        imagedestroy($img);
        return $src;
    }
}



function getImageInfo($src)
{
    return getimagesize($src);
}
/**
* 创建图片，返回资源类�?
* @param string $src 图片路径
* @return resource $im 返回资源类型
* **/
function create($src)
{
    $info=getImageInfo($src);
    switch ($info[2])
    {
        case 1:
            $im=imagecreatefromgif($src);
            break;
        case 2:
            $im=imagecreatefromjpeg($src);
            break;
        case 3:
            $im=imagecreatefrompng($src);
            break;
    }
    return $im;
}


?>
